package com.example.foo.api.web.image;

import java.io.IOException;
import java.io.InputStream;

import com.example.support.oss.AliOssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ruoyi.common.core.domain.AjaxResult;
import com.example.support.oss.AliOssHelper;
import com.example.foo.api.boot.TokenHelper;

@org.springframework.web.bind.annotation.RestController
public class ImageAction {

	public ImageAction() {
	}

	@PostMapping("/api/images")
	public AjaxResult createImage(@RequestParam("albumId") Long albumId, @RequestParam("file") MultipartFile multipartFile) {
		Long loginedUserId = TokenHelper.verifyToken();

		//
		if (albumId == null) {
			return AjaxResult.error(400, "albumId must not be null");
		}
		if (multipartFile == null || multipartFile.isEmpty()) {
			return AjaxResult.error(400, "file must not be null");
		}

		//
		String name = multipartFile.getOriginalFilename();
		String mime = multipartFile.getContentType();
		Long size = multipartFile.getSize();
		String destPath = "a" + albumId.toString() + "/" + AliOssHelper.destPath(name);
		Long userId = loginedUserId;

		//
		String url = alioss(multipartFile, destPath);

		return AjaxResult.successData(url);
	}
	/*
	@Autowired(required = false)
	AliOssProperties aliOssProperties;
	private final OSS ossClient = new OSSClientBuilder().build(aliOssProperties.getEndpoint(), aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret());
	private String alioss(MultipartFile multipartFile, String destPath) {
		InputStream inputStream;
		try {
			inputStream = multipartFile.getInputStream();
		} catch (IOException e) {
			throw new RuntimeException("上传文件失败", e);
		}

		ossClient.putObject(aliOssProperties.getBucketName(), destPath, inputStream);

		String url = aliOssProperties.getWeburl() + "/" + destPath;
		return url;
	} */

	//TODO alioss 先放这
	private final String endpoint = "https://oss-cn-shenzhen.aliyuncs.com";
	private final String accessKeyId = "LTAImKtwGUo7fEJY";
	private final String accessKeySecret = "zihDgOpqpUHIGtpnuU6As5hdxaBtTF";
	private final OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
	private final String bucketName = "xckj-auto-file-res";
	private final String baseUrl = "https://"+bucketName+".oss-cn-shenzhen.aliyuncs.com";
	private String alioss(MultipartFile multipartFile, String destPath) {
		InputStream inputStream;
		try {
			inputStream = multipartFile.getInputStream();
		} catch (IOException e) {
			throw new RuntimeException("上传文件失败", e);
		}

		ossClient.putObject(bucketName, destPath, inputStream);

		String url = this.baseUrl + "/" + destPath;
		return url;
	}

}
